home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: random number
- Date: Tue, 06 Feb 96 20:03:59 GMT
- Organization: none
- Message-ID: <823637039snz@genesis.demon.co.uk>
- References: <3115D5B3.41C6@bazis.nl>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <3115D5B3.41C6@bazis.nl> fkorntne@bazis.nl "Franz Korntner" writes:
-
- >> >Hi,
- >> >Could anybody help me to generate some code to produce
- >> >a random number between -3 and 3 ?
- >> >I'm trying to use rand(), but since it doesn't receive
- >>
- >> Each time you call rand map the result into the interval -3 ... 3.
- >> You can do this, for example, as follows:
- >>
- >> r = (rand() % 7) - 3;
- >>
- >> If you are using rand be sure and read about the role of srand
- >> in "initializing" the sequence of random numbers that are generated.
- >
- >You are using rand()%7 to get a number in the range 0..7 but this method is
- >incorrect. Performing operations on random numbers is okay as long as all
- >bits of the number are included in the operation.
-
- Actually in this case they are (since 7 is odd)! :-)
-
- It is a bad approach in general though.
-
- >It is known to be
- >dangerous to extract bits from a pseudo-random number and assume that those
- >bits have random properties. Even worse, it is also known that the less
- >significant bits of some random number generators are not random at all! In
- >this case you are selecting the 3 most less significant bits of the number,
- >the worst choice that could have been made.
-
- (rand() & 7) or (rand() % 8) would do as you say and be a bad thing.
-
- A better solution is to use the
- >magnitude of the random number, but such operations are implemention
- >dependent (overflows, and such) as in:
- > (rand()*7)/(MAXRAND+1)
-
- The FAQ contains better approaches.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-